package com.gopay.common.mq.converter;

import org.apache.activemq.command.ActiveMQObjectMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import java.io.Serializable;

/**
 * 消息对象 <- -> ActiveMq消息
 */
public class MsgConverter<T extends Serializable> implements MessageConverter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Message --> 泛型T
     */
    @Override
    public T fromMessage(Message message) throws JMSException, MessageConversionException {
        if (logger.isDebugEnabled()) {
            logger.debug("Receive JMS message :" + message);
        }
        if (message instanceof ObjectMessage) {
            ObjectMessage oMsg = (ObjectMessage) message;
            if (oMsg instanceof ActiveMQObjectMessage) {
                ActiveMQObjectMessage aMsg = (ActiveMQObjectMessage) oMsg;

                return (T)aMsg.getObject();
            } else {
                logger.error("Message:${} is not a instance of ActiveMQObjectMessage." + message.toString());
                throw new JMSException("Message:" + message.toString() + "is not a instance of ActiveMQObjectMessage." + message.toString());
            }
        } else {
            logger.error("Message:${} is not a instance of ObjectMessage." + message.toString());
            throw new JMSException( "Message:" + message.toString() + "is not a instance of ObjectMessage." + message.toString());
        }
    }

    /**
     * 泛型T --> Message
     */
    @Override
    public Message toMessage(Object obj, Session session) throws JMSException, MessageConversionException {
        if (logger.isDebugEnabled()) {
            logger.debug("Convert object to JMS message:${}" + obj.toString());
        }

        ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
        msg.setObject((T) obj);
        return msg;

    }

}
